package cn.xy.base.server.web.security;

import cn.hutool.json.JSONUtil;
import cn.xy.commons.constant.Consts;
import cn.xy.commons.core.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;

/**
 * 认证失败处理
 *
 * @author xy
 */
@Component
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {

    private static final String JSON_CONTENT_TYPE = "application/json;charset=UTF-8";

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        try {
            OutputStream os = response.getOutputStream();
            String jsonStr = JSONUtil.toJsonStr(Result.error(Consts.FORBIDDEN, "无法访问系统资源:" + request.getRequestURI()));
            os.write(jsonStr.getBytes(StandardCharsets.UTF_8));
            response.setContentType(JSON_CONTENT_TYPE);
        } catch (Exception ex) {
            log.warn("exception=" + ex);
        }
    }

}
